package com.ruicar.afs.cloud.seats.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.common.core.security.dto.UserInfo;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.seats.condition.GroupUserCondition;
import com.ruicar.afs.cloud.seats.condition.IPageCondition;
import com.ruicar.afs.cloud.seats.condition.ReleaseGroupCondition;
import com.ruicar.afs.cloud.seats.condition.SysUserDto;
import com.ruicar.afs.cloud.seats.entity.BaseHoliday;
import com.ruicar.afs.cloud.seats.entity.OpraHoliday;
import com.ruicar.afs.cloud.seats.entity.PostChangeLog;
import com.ruicar.afs.cloud.seats.entity.UserCollocation;
import com.ruicar.afs.cloud.seats.feign.UserDetailsInfoFeign;
import com.ruicar.afs.cloud.seats.mapper.UserCollocationMapper;
import com.ruicar.afs.cloud.seats.service.BaseHolidayService;
import com.ruicar.afs.cloud.seats.service.OpraHolidayService;
import com.ruicar.afs.cloud.seats.service.PostChangeLogService;
import com.ruicar.afs.cloud.seats.service.UserCollocationService;
import com.ruicar.afs.cloud.seats.util.ApprovalAuthority;
import com.ruicar.afs.cloud.seats.util.JobTag;
import com.ruicar.afs.cloud.seats.util.PostStatus;
import com.ruicar.afs.cloud.seats.util.WorkFlag;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tiankai
 * @Describe 用户参数配置接口
 * Created on 2020-06-18
 */
@Slf4j
@RestController
@RequestMapping("/group")
@AllArgsConstructor
@Api(description = "用户参数配置接口")
public class UserCollocationController {

    private UserCollocationService service;
    private UserCollocationMapper mapper;
    private UserDetailsInfoFeign feign;
    private WorkflowService workflowService;
    private PostChangeLogService logService;
    private OpraHolidayService holidayService;
    private BaseHolidayService baseHolidayService;

    @RequestMapping(value = "/setUserCollocation", method = RequestMethod.POST)
    @ApiOperation(value = "保存参数值")
    public IResponse<UserCollocation> setUserCollocation(@RequestBody UserCollocation userCollocation) {
        UserCollocation collocation = service.getOne(Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getLoginName, userCollocation.getLoginName()));
        if (ObjectUtil.isNull(collocation)) {
            collocation = new UserCollocation();
            collocation.setUserId(userCollocation.getUserId());
            collocation.setLoginName(userCollocation.getLoginName());
        }
        collocation.setPostStatus(userCollocation.getPostStatus());
        collocation.setUserRealName(userCollocation.getUserRealName());
        if (userCollocation.getTotalWeight() != null) {
            WorkFlowResponse workFlowResponse = workflowService.changeTotalWeight(userCollocation.getLoginName(), userCollocation.getTotalWeight().intValue());
            if (workFlowResponse.getSuccess() == 1 && ObjectUtil.isNotNull(workFlowResponse)) {
                collocation.setTotalWeight(userCollocation.getTotalWeight());
            }
        }
        if (StringUtil.isNotEmpty(userCollocation.getAgent())) {
            collocation.setAgentLoginName(userCollocation.getAgent().split(",")[0]);
            collocation.setAgent(userCollocation.getAgent().split(",")[1]);
        }else{
            collocation.setAgentLoginName("");
            collocation.setAgent("");
        }
        if (StringUtil.isNotEmpty(userCollocation.getGroupLeader())) {
            collocation.setGroupLeaderLoginName(userCollocation.getGroupLeader().split(",")[0]);
            collocation.setGroupLeader(userCollocation.getGroupLeader().split(",")[1]);
        }else{
            collocation.setGroupLeaderLoginName("");
            collocation.setGroupLeader("");
        }
        if (StringUtil.isNotEmpty(userCollocation.getAgentGroupLeader())) {
            collocation.setAgentGroupLeaderLoginName(userCollocation.getAgentGroupLeader().split(",")[0]);
            collocation.setAgentGroupLeader(userCollocation.getAgentGroupLeader().split(",")[1]);
        }else{
            collocation.setAgentGroupLeaderLoginName("");
            collocation.setAgentGroupLeader("");
        }
        collocation.setJobTag(JobTag.NO.getCode());
        collocation.setApprovedAmount(userCollocation.getApprovedAmount());
        service.saveOrUpdate(collocation);
        return new IResponse().setData(true);
    }

    @GetMapping(value = {"/queryUserCollocation"})
    @ApiOperation(value = "查看用户配置")
    public IResponse<UserCollocation> queryUserCollocation(@ModelAttribute UserCollocation userCollocation) {
        UserCollocation collocation = service.getOne(Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getUserId, userCollocation.getUserId()));
        return IResponse.success(collocation);
    }

    @GetMapping(value = {"/queryUserCollocationList"})
    @ApiOperation(value = "查看用户配置列表")
    public IResponse<UserCollocation> queryUserCollocationList(@RequestParam(value = "userId") String userId) {
        List<UserCollocation> list = mapper.getUserCollocationList(userId);
        return IResponse.success(list);
    }

    @GetMapping(value = {"/getUserDetailsInfo"})
    @ApiOperation(value = "查看用户详情")
    public IResponse<UserCollocation> getUserDetailsInfo(@ModelAttribute ReleaseGroupCondition condition) {
        String username = SecurityUtils.getUsername();//获取当前用户登录名
        String depId = "";//部门编号
        IResponse<List<SysUserDto>> list = feign.getAllUser();
        List<SysUserDto> sysUserDtoList = list.getData();
        List<SysUserDto> MemberArticleBeanPage = new ArrayList();
        if (sysUserDtoList != null && !sysUserDtoList.isEmpty()) {
            for (SysUserDto sysUserDto : sysUserDtoList) {
                sysUserDto.setCurrentLogin(username);
                if (username.equals(sysUserDto.getUsername())) {
                    depId = sysUserDto.getDeptId();
                }
                UserCollocation collocation = service.getOne(Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getLoginName, sysUserDto.getUsername()));
                if (ObjectUtil.isNotNull(collocation)) {
                    sysUserDto.setPostStatus(collocation.getPostStatus());
                    sysUserDto.setTotalWeight(collocation.getTotalWeight());
                    sysUserDto.setAgentLoginName(collocation.getAgentLoginName());
                    sysUserDto.setAgent(collocation.getAgent());
                    sysUserDto.setGroupLeaderLoginName(collocation.getGroupLeaderLoginName());
                    sysUserDto.setGroupLeader(collocation.getGroupLeader());
                    sysUserDto.setAgentGroupLeaderLoginName(collocation.getAgentGroupLeaderLoginName());
                    sysUserDto.setAgentGroupLeader(collocation.getAgentGroupLeader());
                    sysUserDto.setApprovedAmount(collocation.getApprovedAmount());
                }
                sysUserDto.setRoleName(this.getRoleName(sysUserDto.getUsername()));
            }
            if (condition.getUserName() != null && !condition.getUserName().isEmpty()) {
                sysUserDtoList = sysUserDtoList.stream().filter(d ->
                {
                    if (d.getUserRealName().contains(condition.getUserName()) || d.getUsername().equals(condition.getUserName())) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
            }
            if (condition.getPostStatus() != null && !condition.getPostStatus().isEmpty()) {
                if (PostStatus.NO.getCode().equals(condition.getPostStatus())) {
                    sysUserDtoList = sysUserDtoList.stream().filter(d ->
                            {
                                if (d.getPostStatus()==null) {
                                    return true;
                                } else if(d.getPostStatus().equals(condition.getPostStatus()) || "".equals(d.getPostStatus())){
                                    return true;
                                }else{
                                    return false;
                                }
                            }).collect(Collectors.toList());
                } else {
                    sysUserDtoList = sysUserDtoList.stream().filter(d ->
                    {
                        if (d.getPostStatus()!=null&&d.getPostStatus().equals(condition.getPostStatus())) {
                            return true;
                        } else {
                            return false;
                        }
                    }).collect(Collectors.toList());
                }
            }
            if (condition.getDeptId() != null && !condition.getDeptId().isEmpty()) {
                sysUserDtoList = sysUserDtoList.stream().filter(d ->
                {
                    if (!StringUtils.isEmpty(d.getDeptId()) && d.getDeptId().equals(condition.getDeptId())) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
            }
            String finalDepId = depId;
            sysUserDtoList = authorityAssignment(condition.getApprovalAuthority(), sysUserDtoList, finalDepId, username);
            int currIdx = (condition.getPageNumber() > 1 ? (condition.getPageNumber() - 1) * condition.getPageSize() : 0);
            for (int i = 0; i < condition.getPageSize() && i < sysUserDtoList.size() - currIdx; i++) {
                SysUserDto userDto = sysUserDtoList.get(currIdx + i);
                MemberArticleBeanPage.add(userDto);
            }
        }
        IPageCondition iPageCondition = new IPageCondition();
        iPageCondition.setRecords(MemberArticleBeanPage);
        iPageCondition.setTotal(sysUserDtoList.size());
        return IResponse.success(iPageCondition);
    }

    /**
     * @Describe 数据权限删选
     * Created on 2020-06-08
     * @author tiankai
     */
    public List<SysUserDto> authorityAssignment(String approvalAuthority, List<SysUserDto> sysUserDtoList, String finalDepId, String userName) {
        if (ApprovalAuthority.ADD.getCode().equals(approvalAuthority)) {
            sysUserDtoList = sysUserDtoList.stream().filter(d ->
            {
                if (!StringUtils.isEmpty(d.getDeptId()) && d.getDeptId().equals(finalDepId)) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
        } else if (ApprovalAuthority.EXAMINER.getCode().equals(approvalAuthority)) {
            sysUserDtoList = sysUserDtoList.stream().filter(d -> userName.equals(d.getUsername())).collect(Collectors.toList());
        }
        return sysUserDtoList;
    }

    /**
     * @Describe 数据权限删选
     * Created on 2020-06-08
     * @author tiankai
     */
    public String getRoleName(String username){
        String roleName = "";
        IResponse IResponse = feign.info(username);
        String str3 = JSON.toJSONString(IResponse.getData());
        JSONObject jsonObject = (JSONObject) JSONObject.parse(str3);
        UserInfo userInfo = JSONObject.toJavaObject(jsonObject,UserInfo.class);
        List<RoleVo> list = userInfo.getRoleList();
        if(list!=null&&!list.isEmpty()){
            for(RoleVo roleVo : list){
                roleName = roleVo.getRoleName()+",";
            }
            return roleName.substring(0,roleName.length()-1);
        }
        return roleName;
    }

    @GetMapping(value = {"/getUserJobButton"})
    @ApiOperation(value = "获取用户上离岗按钮权限")
    public IResponse getUserJobButton() {
        long approveId = 4441065934335017601L;
        long loanId = 4441065934335017851L;
        long deptId = SecurityUtils.getUser().getDeptId();
        UserCollocation collocation = null;
        if(deptId==approveId || deptId==loanId){
            collocation = service.getOne(Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getLoginName, SecurityUtils.getUser().getUsername()));
            if(ObjectUtil.isNull(collocation)){
                collocation = new UserCollocation();
                collocation.setLoginName(SecurityUtils.getUser().getUsername());
                collocation.setPostStatus(PostStatus.NO.getCode());
            }
            return new IResponse().setData(collocation);
        }else{
            return new IResponse().setData(null);
        }
    }

    @RequestMapping(value = "/updateUserCollocation", method = RequestMethod.POST)
    @ApiOperation(value = "更新用户配置信息")
    public IResponse<UserCollocation> updateUserCollocation(@RequestBody GroupUserCondition userCollocation) {
        PostChangeLog changeLog = new PostChangeLog();
        changeLog.setLoginName(SecurityUtils.getUser().getUsername());
        changeLog.setUserName( SecurityUtils.getUser().getUserRealName());
        changeLog.setPostChangeStatus(userCollocation.getPostStatus());
        UserCollocation collocation = service.getOne(Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getLoginName, SecurityUtils.getUser().getUsername()));
        if(ObjectUtil.isNotNull(collocation)){
            collocation.setPostStatus(userCollocation.getPostStatus());
        }else{
            collocation = new UserCollocation();
            collocation.setLoginName(SecurityUtils.getUser().getUsername());
            collocation.setPostStatus(userCollocation.getPostStatus());
        }
        if(PostStatus.YES.getCode().equals(userCollocation.getPostStatus())){
            changeLog.setChangeRemarks("手动上岗");
            SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
            String year = date.format(new Date()).substring(0,4);
            String month = date.format(new Date()).substring(5,7);
            String day = date.format(new Date()).substring(8,10);
            OpraHoliday opraHoliday = holidayService.getOne(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getLoginName, SecurityUtils.getUser().getUsername()).eq(OpraHoliday::getYear, year).eq(OpraHoliday::getMonth, month).eq(OpraHoliday::getDay, day));
            if(ObjectUtil.isNotNull(opraHoliday)&& WorkFlag.REST_FLAG.getCode().equals(opraHoliday.getWorkFlagAm())){
                opraHoliday.setWorkFlagAm(WorkFlag.WORK_FLAG.getCode());
                opraHoliday.setWorkFlagPm(WorkFlag.WORK_FLAG.getCode());
                holidayService.saveOrUpdate(opraHoliday);
            }else if(ObjectUtil.isNull(opraHoliday)){
                BaseHoliday baseHoliday = baseHolidayService.getOne(Wrappers.<BaseHoliday>query().lambda().eq(BaseHoliday::getYear, year).eq(BaseHoliday::getMonth, month).eq(BaseHoliday::getDay, day));
                if(ObjectUtil.isNotNull(baseHoliday)&& WorkFlag.REST_FLAG.getCode().equals(baseHoliday.getWorkFlagAm())){
                    opraHoliday = new OpraHoliday();
                    opraHoliday.setLoginName(SecurityUtils.getUser().getUsername());
                    opraHoliday.setWorkFlagPm(WorkFlag.WORK_FLAG.getCode());
                    opraHoliday.setWorkFlagAm(WorkFlag.WORK_FLAG.getCode());
                    opraHoliday.setTimeAm(baseHoliday.getTimeAm());
                    opraHoliday.setTimePm(baseHoliday.getTimePm());
                    opraHoliday.setYear(year);
                    opraHoliday.setMonth(month);
                    opraHoliday.setDay(day);
                    opraHoliday.setWeek(baseHoliday.getWeek());
                    holidayService.saveOrUpdate(opraHoliday);
                }
            }
        }else{
            changeLog.setChangeRemarks(userCollocation.getChangeRemarks());
        }
        collocation.setJobTag(JobTag.NO.getCode());
        service.saveOrUpdate(collocation);
        logService.saveOrUpdate(changeLog);
        return new IResponse().setData(true);
    }
}